<template>
  <div class="tags-view">
    <div
      v-for="(tag, index) in tags"
      :key="tag.path"
      :class="['tag-item', { active: tag.path === $route.path }]"
      @contextmenu.prevent="showMenu($event, tag)"
    >
      <span @click="handleClick(tag)">{{ tag.meta.title }}</span>
      <span
        v-if="tag.path !== '/dashboard'"
        class="close-btn"
        @click.stop="handleClose(tag, index)"
      >×</span>
    </div>
    <ul v-if="menuVisible" class="tag-menu" :style="{ left: menuX + 'px', top: menuY + 'px' }" @click.stop>
      <li @click="closeOthers">关闭其它</li>
      <li @click="closeAll">关闭所有</li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { computed, ref, onUnmounted } from 'vue'
import { useTagsViewStore } from '@/stores/tagsView'

const $route = useRoute()
const $router = useRouter()
const tagsViewStore = useTagsViewStore()
const tags = computed(() => tagsViewStore.tags)

function handleClick(tag) {
  if (tag.path !== $route.path) {
    $router.push(tag.path)
  }
}
function handleClose(tag, index) {
  tagsViewStore.removeTag(tag.path)
  // 关闭当前页时，自动跳转到最后一个标签或首页
  if (tag.path === $route.path) {
    const nextTag = tags.value[index - 1] || tags.value[index] || { path: '/dashboard' }
    $router.push(nextTag.path)
  }
}

// 右键菜单
const menuVisible = ref(false)
const menuX = ref(0)
const menuY = ref(0)
const menuTag = ref(null)

function showMenu(e, tag) {
  if (tag.path === '/dashboard') return
  menuVisible.value = true
  menuX.value = e.clientX
  menuY.value = e.clientY
  menuTag.value = tag
}
function hideMenu() { menuVisible.value = false }
function closeOthers() {
  tagsViewStore.removeOthers(menuTag.value.path)
  hideMenu()
  if (menuTag.value.path !== $route.path) $router.push(menuTag.value.path)
}
function closeAll() {
  tagsViewStore.removeAll()
  hideMenu()
  $router.push('/dashboard')
}
document.addEventListener('click', hideMenu)
onUnmounted(() => document.removeEventListener('click', hideMenu))
</script>

<style scoped>
.tags-view { display: flex; align-items: center; height: 40px; background: #fff; padding: 0 10px; border-bottom: 1px solid #eee; overflow-x: auto; }
.tag-item { display: flex; align-items: center; background: #f4f6fb; border-radius: 3px; margin-right: 8px; padding: 0 12px; height: 28px; cursor: pointer; font-size: 14px; color: #666; position: relative; user-select: none; }
.tag-item.active { background: #409EFF; color: #fff; }
.close-btn { margin-left: 6px; font-size: 14px; cursor: pointer; }
.tag-menu { position: fixed; z-index: 9999; min-width: 120px; background: #fff; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); padding: 4px 0; list-style: none; }
.tag-menu li { padding: 8px 16px; cursor: pointer; color: #333; font-size: 14px; transition: background 0.2s; }
.tag-menu li:hover { background: #f5f7fa; color: #409EFF; }
</style> 